#include "BlockQueue.hpp"
#include "Task.hpp"
#include <ctime>

int myadd(int x, int y)
{
    return x + y;
}

void* consumer(void* args) // 消费者
{
    BlockQueue<Task>* bqueue = (BlockQueue<Task>*)args;

    while (true)
    {
        // 获取任务
        Task t;
        bqueue->pop(&t);

        // 完成任务
        std::cout << pthread_self() << " cousumer: " << t._x << " + " << t._y << " = " << t() << std::endl;
        sleep(1);
    }

    return nullptr;
}

void* productor(void* args)
{
    BlockQueue<Task>* bqueue = (BlockQueue<Task>*)args;

    while (true)
    {
        // 制作任务
        int x = rand() % 10 + 1;
        usleep(rand() % 1000);
        int y = rand() % 5 + 1;

        Task t(x, y, myadd);

        // 生产任务
        bqueue->push(t);

        // 输入消息
        std::cout << pthread_self() << " prodector: " << t._x << " + " << t._y << " = ?" << std::endl;
    }

    return nullptr;
}

int main()
{
    srand((uint64_t)time(nullptr) ^ getpid() ^ 0x523652);
    BlockQueue<Task>* bqueue = new BlockQueue<Task>();

    pthread_t c[2], p[2];  // c代表消费者, p代表生产者

    pthread_create(c, nullptr, consumer, (void*)bqueue);
    pthread_create(c + 1, nullptr, consumer, (void*)bqueue);
    pthread_create(p, nullptr, productor, (void*)bqueue);
    pthread_create(p + 1, nullptr, productor, (void*)bqueue);

    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);
    return 0;
}
